<template>
  <div>
    <!-- 对话框(添加 / 修改) -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="35%" v-dialogDrag append-to-body>
      <el-form ref="formRef" :model="formData" :rules="formRules" v-loading="formLoading" label-width="130px">
        <el-form-item label="托盘/RFID/箱" prop="code">
          <el-input v-model="formData.code" placeholder="请输入托盘码/RFID编码" size="small"
                    style="width: 200px; margin-right: 10px;" @blur="checkTray"/>
          <el-button @click="checkTray" size="small">扫码</el-button>
        </el-form-item>
        <el-form-item label="调整类型" prop="adjustType">
          <el-radio-group v-model="formData.adjustType" @input="adjustTypeChange">
            <el-radio-button :label="1">合</el-radio-button>
            <el-radio-button :label="2">拆</el-radio-button>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
        <el-table-column label="箱码" align="center" prop="infoCode"/>
        <el-table-column label="产品码" align="center" prop="infoName"/>
        <el-table-column label="数量" align="center" prop="count"/>
        <el-table-column label="状态" align="center" prop="status" :formatter="statusFormat"/>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button v-if="formData.adjustType" type="danger" @click="scanMaterial">{{ adjustText }}物料</el-button>
        <el-button type="primary" @click="submitForm" :disabled="formLoading">确 定</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 对话框(添加 / 修改) -->
    <ScanMaterialForm ref="scanMaterialRef" @success="getMaterial"/>
    <!-- 对话框(添加 / 修改) -->
    <TrayForm ref="trayFormRef" @success="getList"/>
  </div>
</template>

<script>
import {DICT_TYPE} from "@/utils/dict";
import {create, getMaterialBoxByCode, getMaterialOrBox, getTrayRfidInfo, manualAdjust} from "@/api/hs/scan";
import ScanMaterialForm from './ScanMaterialForm.vue';
import TrayForm from './TrayForm.vue';

export default {
  name: "ManualForm",
  computed: {
    DICT_TYPE() {
      return DICT_TYPE
    }
  },
  components: {
    ScanMaterialForm,
    TrayForm
  },
  data() {
    return {
      // 弹出层标题
      dialogTitle: "",
      // 是否显示弹出层
      dialogVisible: false,
      // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
      formLoading: false,
      // 遮罩层
      loading: false,
      // 信息列表
      list: [],
      // 表单参数
      formData: {
        code: undefined,
        adjustType: undefined,
      },
      statusList: [
        {
          label: "在库",
          value: 1
        },
        {
          label: "增加",
          value: 2
        },
        {
          label: "减少",
          value: 3
        }
      ],
      adjustText: "",
      // 表单校验
      formRules: {
        code: [{required: true, message: '托盘/RFID/箱不能为空', trigger: 'blur'}],
        adjustType: [{required: true, message: '调整类型不能为空', trigger: 'blur'}],
      },
    };
  },
  methods: {
    /** 打开弹窗 */
    async open() {
      this.dialogVisible = true;
      this.reset();
    },
    /** 校验托盘 */
    async checkTray() {
      await this.$refs["formRef"].validate();
      if (this.formData.adjustType === 1) {
        const res = await getTrayRfidInfo(this.formData.code);
        if (!res.data) {
          this.list = []
          this.$confirm('这是一个新托盘, 是否绑定托盘?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            create(this.formData.code).then(res => {
              if (res.code === 0) {
                this.$message.success("托盘创建成功");
                return true;
              }
            })
          }).catch(() => {
          });
          return false;
        }
      }
      await this.getList();
      return true;
    },
    /** 查询列表 */
    async getList() {
      try {
        this.loading = true;
        const res = await getMaterialOrBox('', this.formData.code);
        this.list = res.data;
        this.list.forEach(item => {
          item.status = 1;
        });
      } finally {
        this.loading = false;
      }
    },
    statusFormat(row) {
      if (!row.status) {
        return '未设置';
      }
      for (const status of this.statusList) {
        if (row.status === status.value) {
          return status.label;
        }
      }
      return '未知【' + row.status + '】';
    },
    /** 调整类型改变 */
    adjustTypeChange(value) {
      if (value === 1) {
        this.adjustText = '添加'
      }
      if (value === 2) {
        this.adjustText = '减少'
      }
      this.checkTray();
    },
    /** 扫描物料 */
    scanMaterial() {
      this.$refs["scanMaterialRef"].open();
    },
    /** 获取物料 */
    async getMaterial(value) {
      const res = await getMaterialBoxByCode(value)
      if (this.formData.adjustType === 1) {
        res.data.status = 2
      }
      if (this.formData.adjustType === 2) {
        res.data.status = 3
      }
      this.list.push(res.data)
    },
    /** 提交按钮 */
    async submitForm() {
      // 校验主表
      await this.$refs["formRef"].validate();
      this.formLoading = true;
      try {
        const data = this.formData;
        data.list = this.list
        await manualAdjust(data);
        this.$modal.msgSuccess("调整成功");
        this.dialogVisible = false;
        this.$emit('success');
      } finally {
        this.formLoading = false;
      }
    },
    /** 表单重置 */
    reset() {
      this.formData = {
        code: undefined,
        adjustType: undefined,
      };
      this.list = [];
      this.resetForm("formRef");
    }
  }
};
</script>
